package com.example.myblog.controller;

import com.example.myblog.dao.TagMapper;
import com.example.myblog.entity.Blog;
import com.example.myblog.entity.Tag;
import com.example.myblog.service.BlogService;
import com.example.myblog.service.TagService;
import com.example.myblog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;
    @GetMapping("/index")
    public String index(Model model,Integer page){
        page = page==null?0:page;
        model.addAttribute("page",blogService.listBlog(page,5));
        model.addAttribute("blogs",blogService.topRecNum(9));
        model.addAttribute("types",typeService.listTopNum(5));
        model.addAttribute("tags",tagService.listTopNum(9));
        return "index";
    }

    @PostMapping("/search")
    public String search(String query,Integer page,Model model){
        page = page==null? 0:page;
        model.addAttribute("page",blogService.listSearch(query,page));
        model.addAttribute("query",query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Integer id,Model model) {
        Blog blog = blogService.findById(id);
        model.addAttribute("blog", blog);
        Integer views = blog.getViews();
        views = views==null? 1 : ++views;
        blog.setViews(views);
        blogService.update(blog);
        return "blog";
    }

}
